// 协议分发器
import {Pack} from "./Pack";
import Singleton from "db://assets/scripts/common/Singleton";

export class ProtoDispatcher extends Singleton {

    // 解码器 cmdId => function
    private decoders: Map<number, (data: Uint8Array) => any> = new Map();
    // 协议处理方法 cmdId => function
    private handlers: Map<number, (data: any) => any> = new Map();

    // 注册解码器
    static registerDecoder(cmdId: number, decoder: any) {
        this.getInstance().decoders.set(cmdId, decoder);
    }

    // 注册协议处理方法
    static registerHandler(cmdId: number, handler: any) {
        this.getInstance().handlers.set(cmdId, handler);
    }

    // 协议分发
    dispatch(pack: Pack) {
        const decoder = this.decoders.get(pack.cmdId);
        if (decoder == null) {
            console.error(`没有对应的协议解码器。cmdId: ${pack.cmdId}`);
            return;
        }
        const handler = this.handlers.get(pack.cmdId);
        if (handler == null) {
            console.error(`没有对应的协议处理器。cmdId: ${pack.cmdId}`);
            return;
        }
        const data: any = decoder(pack.data);
        handler(data);
    }


}